struct cmp {
    bool operator()(pair<int, int>& m, pair<int, int>& n) {
        return m.second > n.second;
    }
};
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        map<int, int> rec;
        priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q;

        for (int n: nums) {
            rec[n]++;
        }
        for (auto& it: rec) {
            q.emplace(it.first, it.second);
            if (q.size() > k) q.pop();
        }
        while (!q.empty()) {
            res.push_back(q.top().first);
            q.pop();
        }
        return res;
    }
};